import 'package:sqflite/sqflite.dart';

import '../model/cn_anchor_model.dart';

///通话记录数据库
class CnDatabaseHelper {
  factory CnDatabaseHelper() => getInstance()!;
  static CnDatabaseHelper? _instance;
  static Database? _database;
  static const String _dataBaseName = 'AnchorRecordsCache.db';
  static const String _anchorTableName = 'AnchorRecords';

  CnDatabaseHelper._internal();

  static CnDatabaseHelper? getInstance() {
    _instance ??= CnDatabaseHelper._internal();
    return _instance;
  }

  Future<void> openDataBase() async {
    // 表不存在，创建表
    _database = await openDatabase(_dataBaseName, version: 1,
        onCreate: (Database db, int version) async {
      await db.execute(
          'CREATE TABLE AnchorRecords (id INTEGER PRIMARY KEY,nickname TEXT,userId TEXT,avatar TEXT,country TEXT,imageMapPaths TEXT,gender INTEGER,callCoins INTEGER,age INTEGER,followNum INTEGER,isFollow BOOLEAN)');
    });
  }

  ///插入主播记录数据

  Future<void> insertAnchorRecord({
    required String nickname,
    required String userId,
    required String avatar,
    required String country,
    required String imageMapPaths,
    required int gender,
    required int callCoins,
    required int age,
    required int followNum,
    required bool isFollow,
  }) async {
    Map<String, dynamic> record = {
      'nickname': nickname,
      'userId': userId,
      'imageMapPaths': imageMapPaths,
      'avatar': avatar,
      'country': country,
      'age': age,
      'gender': gender,
      'callCoins': callCoins,
      'followNum': followNum,
      'isFollow': isFollow,
    };

    if (_database == null) {
      await openDataBase();
    }
    await _database?.insert(_anchorTableName, record);
  }

  Future<List<CnAnchorModel>> queryAllAnchorRecords() async {
    if (_database == null) {
      await openDataBase();
    }
    List<Map<String, dynamic>>? results =
        await _database?.query(_anchorTableName);
    List<CnAnchorModel> resultData = [];
    if (null != results) {
      for (int i = 0; i < (results.length); i++) {
        resultData.add(CnAnchorModel.coverFromJson(results[i]));
      }
    }
    return resultData;
  }

  Future<void> deleteAnchorRecord() async {
    if (_database == null) {
      await openDataBase();
    }
    await _database?.delete(_anchorTableName);
  }

  Future deleteUser(String userId) async {
    if (_database == null) {
      await openDataBase();
    }
    await _database
        ?.delete(_anchorTableName, where: 'userId = ?', whereArgs: [userId]);
  }

  Future updateUserInFollow(String userId, bool isFollow) async {
    if (_database == null) {
      await openDataBase();
    }
    await _database?.update(
        _anchorTableName, <String, dynamic>{'isFollow': isFollow},
        where: 'userId = ?', whereArgs: [userId]);
  }
}
